package com.cjlgb.design.oauth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cjlgb.design.common.core.constant.CacheName;
import com.cjlgb.design.common.core.constant.InnerApps;
import com.cjlgb.design.common.mybatis.service.impl.BaseServiceImpl;
import com.cjlgb.design.oauth.entity.Oauth2AccountDetails;
import com.cjlgb.design.oauth.mapper.Oauth2AccountDetailsMapper;
import com.cjlgb.design.oauth.service.OauthAccountService;
import com.cjlgb.design.upms.api.feign.UserFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author WFT
 * @date 2019/5/19
 * description: 用户详细配置实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = CacheName.OAUTH_USER_DETAILS)
public class OauthAccountServiceImpl extends BaseServiceImpl<Oauth2AccountDetailsMapper,Oauth2AccountDetails>
        implements UserDetailsService, OauthAccountService {

    private final UserFeign userFeign;

    @Override
    @Cacheable
    public UserDetails loadUserByUsername(String username){
        Oauth2AccountDetails details = this.getOne(
                Wrappers.<Oauth2AccountDetails>lambdaQuery().eq(Oauth2AccountDetails::getUsername, username)
        );
        if (null == details){
            throw new UsernameNotFoundException(username);
        }
        //  获取权限列表
        Collection<String> authorities = this.userFeign.getAccountAuthorities(details.getId(), InnerApps.OAUTH_SERVER);
        details.setAuthorities(this.createAuthorityList(authorities));
        return details;
    }

    @Override
    @CacheEvict
    public void deleteCacheByUsername(String username) {

    }

    @Override
    @CacheEvict(key = "#username")
    public void editLockFlag(String username, Integer lockFlag) {
        this.update(
                Wrappers.<Oauth2AccountDetails>lambdaUpdate()
                        .eq(Oauth2AccountDetails::getUsername, username)
                        .set(Oauth2AccountDetails::getLockFlag, lockFlag)
        );
    }

    private Collection<? extends GrantedAuthority> createAuthorityList(Collection<String> authorities){
        Collection<GrantedAuthority> list = new ArrayList<>(authorities.size());
        authorities.forEach(authority -> list.add(new SimpleGrantedAuthority(authority)));
        return list;
    }
}
